﻿using RpcCentral.Common;
using RpcCentral.DAL;
using RpcCentral.Model;
using RpcHelper;
using RpcModel;

namespace RpcCentral.Collect.Controller
{
    public class RpcVerController : DataSyncClass
    {
        private readonly long _RpcMerId;
        private readonly long _VerNum;
        private readonly long _SystemTypeId;
        private long _VerId;
        private bool _IsEnable = false;
        private Dictionary<long, VerRoute> _VerRoute;

        public RpcVerController(long rpcMerId, long sysTypeId, long ver)
        {
            _RpcMerId = rpcMerId;
            _VerNum = ver;
            _SystemTypeId = sysTypeId;
        }
        private IServiceVerConfigDAL _VerConfigDAL
        {
            get => UnityHelper.Resolve<IServiceVerConfigDAL>();
        }
        private IServiceVerRouteDAL _VerRouteDAL
        {
            get => UnityHelper.Resolve<IServiceVerRouteDAL>();
        }
        protected override void SyncData()
        {
            this._VerId = _VerConfigDAL.GetVerId(_VerNum, _SystemTypeId, _RpcMerId);
            if (_VerId == 0)
            {
                _IsEnable = false;
                return;
            }
            VerRoute[] routes = _VerRouteDAL.GetVerRoute(this._VerId);
            _VerRoute = routes.ToDictionary(a => a.SystemTypeId, a => a);
            _IsEnable = true;
        }


        public ServerConfig[] Filters(long sysTypeId, ServerConfig[] servers)
        {
            if (!_IsEnable || servers == null)
            {
                return servers;
            }
            else if (!_VerRoute.TryGetValue(sysTypeId, out VerRoute route))
            {
                return servers;
            }
            else
            {
                return servers.FindAll(a => route.IsValid(a.VerNum));
            }
        }
    }
}
